import { LoginWrapper } from "./style";
import {
  Form,
  Input,
  Button,
  Checkbox,
  Modal,
  Message,
} from "@arco-design/web-react";
import {
  IconUser,
  IconLock,
  IconSafe,
  IconQq,
  IconWechat,
  IconWeibo,
} from "@arco-design/web-react/icon";
import { memo, useEffect, useState } from "react";
import {
  fetchGetLoginAction,
  fetchGetLoginCodeAction,
  // fetchGetUserInfoAction,
} from "../../store/modules/login";
import { useAppDispatch, useAppSelector } from "../../store";
import weixin from "../../assets/img/weixin.jpg";
import qq from "../../assets/img/qq.jpg";
import { useNavigate } from "react-router-dom";
import { clearCurrentToken } from "../../service/modules/login";
const FormItem = Form.Item;

const LoginPage = () => {
  const [isLogin, setIsLogin] = useState(true);
  const [captchaImage, setCaptchaImage] = useState("");
  const [currentUuid, setCurrentUuid] = useState("");
  const [currentImage, setCurrentImage] = useState("");
  const [visible, setVisible] = useState(false);
  const [loginForm] = Form.useForm();
  const dispatch = useAppDispatch();
  const navigate = useNavigate();
  // const location = useLocation();
  const { captcha } = useAppSelector((state) => state.login);
  // console.log(location.pathname);

  //点击图标处理
  const handleIconClick = (type: string) => {
    switch (type) {
      case "qq":
        setCurrentImage(qq);
        break;
      case "weixin":
        setCurrentImage(weixin);
        break;
      case "weibo":
        setCurrentImage("");
        break;
      default:
        return;
    }
    setVisible(true);
  };
  // console.log(location.pathname);

  useEffect(() => {
    refreshCaptcha();
    clearCurrentToken();
  }, []);
  useEffect(() => {
    if (captcha.img) {
      setCaptchaImage(`data:image/jpeg;base64,${captcha.img}`);
    }
  }, [captcha.img]);

  const refreshCaptcha = async () => {
    dispatch(fetchGetLoginCodeAction());
    const result = await dispatch(fetchGetLoginCodeAction());
    setCurrentUuid(result.payload.uuid);
  };

  const handleSubmit = async (values: {
    loginUserName: string;
    loginPassWord: string;
    loginCode: string;
    uuid: string;
  }) => {
    try {
      const res = await dispatch(
        fetchGetLoginAction({
          username: values.loginUserName,
          password: values.loginPassWord,
          code: values.loginCode,
          uuid: currentUuid,
        })
      ).unwrap();
      if (res.code === 200) {
        Message.success("登录成功");
        navigate("/home");
      } else {
        if (res.code === 500) {
          Message.error("验证码输入错误");
          refreshCaptcha();
        }
      }
    } catch (err) {
      console.log(err);
      Message.error("登入失败");
    }
  };

  return (
    <LoginWrapper isLogin={isLogin}>
      <Modal
        visible={visible}
        onOk={() => setVisible(false)}
        onCancel={() => setVisible(false)}
        // autoFocus={false}
        // focusLock={true}
      >
        <div style={{ textAlign: "center", userSelect: "none" }}>
          <img
            src={currentImage}
            style={{ maxWidth: "100%", maxHeight: "300px" }}
          />
          <p style={{ marginTop: "10px" }}>联系作者可以扫描二维码</p>
        </div>
      </Modal>
      <h2 style={{ position: "absolute", top: "200px", fontSize: "30px" }}>
        术后康复管理系统
      </h2>

      <div className="shell">
        <div className="container create-container">
          <Form>
            <h2 className="form-title">创建账号</h2>
            <div className="form-icons">
              <i
                className="iconfont icon-QQ"
                onClick={() => handleIconClick("qq")}
              >
                <IconQq />
              </i>
              <i
                className="iconfont icon-weixin"
                onClick={() => handleIconClick("weixin")}
              >
                <IconWechat />
              </i>
              <i
                className="iconfont icon-weibo"
                onClick={() => handleIconClick("")}
              >
                <IconWeibo />
              </i>
            </div>
            <span className="form-span">选择一种方式创建账户</span>
            <FormItem>
              <Input
                placeholder="请输入用户名"
                prefix={
                  <IconUser
                    style={{
                      marginLeft: "5px",
                      width: "20px",
                      height: "20px",
                    }}
                  />
                }
              />
            </FormItem>
            <FormItem>
              <Input.Password
                placeholder="请输入密码"
                prefix={
                  <IconLock
                    style={{
                      marginLeft: "5px",
                      width: "20px",
                      height: "20px",
                    }}
                  />
                }
              />
            </FormItem>
            <FormItem>
              <Checkbox>
                <span style={{ marginLeft: "10px", alignItems: "center" }}>
                  我已阅读用户协议
                </span>
              </Checkbox>
            </FormItem>

            <Button
              type="primary"
              shape="round"
              style={{ width: "150px", height: "45px", borderRadius: "25px" }}
              onClick={() => Message.info("没有注册接口~")}
            >
              <span className="submit-name">注册</span>
            </Button>
          </Form>
        </div>
        <div className="container login-container">
          <Form form={loginForm} onSubmit={handleSubmit}>
            <h2 className="form-title">登录账号</h2>
            <div className="form-icons">
              <i
                className="iconfont icon-QQ"
                onClick={() => handleIconClick("qq")}
              >
                <IconQq />
              </i>
              <i
                className="iconfont icon-weixin"
                onClick={() => handleIconClick("weixin")}
              >
                <IconWechat />
              </i>
              <i
                className="iconfont icon-weibo"
                onClick={() => handleIconClick("")}
              >
                <IconWeibo />
              </i>
            </div>
            <span className="form-span">选择一种方式登录</span>
            <FormItem
              field="loginUserName"
              rules={[
                {
                  validator(value, cb) {
                    const userNameRegex = /^[\u4e00-\u9fa5a-zA-Z0-9]{4,16}$/;
                    if (!value) {
                      cb("用户名不能为空");
                    } else if (!userNameRegex.test(value)) {
                      cb("用户名格式不正确（4-16位字母/数字/下划线/中文）");
                    } else {
                      cb();
                    }
                  },
                },
              ]}
            >
              <Input
                placeholder="请输入用户名"
                prefix={
                  <IconUser
                    style={{
                      marginLeft: "5px",
                      width: "20px",
                      height: "20px",
                    }}
                  />
                }
              />
            </FormItem>

            <FormItem
              field="loginPassWord"
              rules={[
                {
                  validator(value, cb) {
                    const passwordRegex = /^[a-zA-Z0-9_@#$%^&*!~]{6,20}$/;
                    if (!value) {
                      cb("密码不能为空");
                    } else if (!passwordRegex.test(value)) {
                      cb("密码不符合规范");
                    } else {
                      cb();
                    }
                  },
                },
              ]}
            >
              <Input.Password
                placeholder="请输入密码"
                prefix={
                  <IconLock
                    style={{
                      marginLeft: "5px",
                      width: "20px",
                      height: "20px",
                    }}
                  />
                }
              />
            </FormItem>
            <div style={{ display: "flex", alignItems: "center" }}>
              <FormItem
                field="loginCode"
                rules={[
                  {
                    validator(value, cd) {
                      const codeRegex = /^[0-9]{1,4}$/;
                      if (!value) {
                        cd("请输入验证码");
                        return;
                      } else if (!codeRegex.test(value)) {
                        cd("验证码格式错误");
                      }
                    },
                  },
                ]}
              >
                <Input
                  style={{
                    width: "250px",
                    marginLeft: "-50px",
                  }}
                  placeholder="请输入验证码"
                  prefix={
                    <IconSafe
                      style={{
                        marginLeft: "5px",
                        width: "20px",
                        height: "20px",
                      }}
                    />
                  }
                />
              </FormItem>

              {captchaImage && (
                <img
                  onClick={refreshCaptcha}
                  src={captchaImage}
                  style={{
                    width: "120px",
                    marginLeft: "65px",
                    cursor: "pointer",
                    height: "50px",
                  }}
                />
              )}
            </div>

            <FormItem>
              <Checkbox>
                <span style={{ alignItems: "center", marginLeft: "10px" }}>
                  我已阅读用户协议
                </span>
              </Checkbox>
            </FormItem>

            <Button
              htmlType="submit"
              type="primary"
              shape="round"
              style={{
                width: "150px",
                height: "45px",
                borderRadius: "25px",
                cursor: "pointer",
              }}
            >
              <span className="submit-name">登录</span>
            </Button>
          </Form>
        </div>
        <div className="switch">
          <div className="switch_container login-switch ">
            <h2>Welcome Back!</h2>
            <p className="switch-description">
              已经有账号了嘛，去登录账号来进入前端世界吧
            </p>
            <Button
              type="primary"
              shape="round"
              style={{
                width: "150px",
                height: "45px",
                borderRadius: "25px",
                marginTop: "50px",
              }}
              onClick={() => {
                setIsLogin(true);
              }}
            >
              登录
            </Button>
          </div>
          <div className="switch_container create-switch">
            <h2>Hello Friend!</h2>
            <p className="switch-description">
              去注册一个账号，这样就有机会观看我的前端世界
            </p>
            <Button
              type="primary"
              shape="round"
              style={{
                width: "150px",
                height: "45px",
                borderRadius: "25px",
                cursor: "pointer",
                marginTop: "50px",
              }}
              onClick={() => {
                setIsLogin(false);
                // console.log(isLogin);
              }}
            >
              注册
            </Button>
          </div>
        </div>
      </div>
    </LoginWrapper>
  );
};

export default memo(LoginPage);
